package org.nokatag.tagjava;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.noka.compressor.CssCompressor;
import org.nokatag.system.Concest;

public class CssCompressorTag extends BodyNokaTag{

	private static final long serialVersionUID = 2792428015994840009L;
	private String id = null;
	
	public int doStartTag() throws JspException {
		return EVAL_BODY_BUFFERED;
	}
    public int doAfterBody() throws JspException {
        BodyContent body = this.getBodyContent();
        String    content = body.getString();
        String jbbody = null;
        String key = null;
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        try{
        	key = getKey(request,id);
        	if(key!=null){
            	jbbody = Concest.PAGE_CACHE_JSSORCSS.get(key);
        	}
        	if(jbbody==null){
		        ByteArrayInputStream bin = new ByteArrayInputStream(content.getBytes(Concest.ENCODING));
		        Reader in= new InputStreamReader(bin,Concest.ENCODING);
		        ByteArrayOutputStream out=new ByteArrayOutputStream();
		        CssCompressor css = new CssCompressor(in);
		    	css.compress(out, -1);
		    	jbbody=out.toString(Concest.ENCODING);
		    	if(key!=null)
		    		Concest.PAGE_CACHE_JSSORCSS.put(key, jbbody);
        	}
	        body.clearBody();
	        body.write(jbbody);
	        setBodyContent(body);
        }catch(Exception se){
        	
        }
        return SKIP_BODY;
    }
    
    public int doEndTag()throws JspException{  
        if(super.bodyContent!=null){  
            try{  
                super.bodyContent.writeOut(super.getPreviousOut());    //输出到页面  
            }  
            catch(Exception e){}  
        }  
        return BodyTagSupport.EVAL_PAGE;  
    }
    public String getKey(HttpServletRequest request,String id){
    	if(id==null)
    		return null;
		return request.getContextPath()+request.getServletPath()+"pkey_"+id;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}  
}
